package com.qfan.springaimcpdemo.service;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.qfan.springaimcpdemo.utils.TavilySearch;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.ai.tool.annotation.Tool;
import org.springframework.ai.tool.annotation.ToolParam;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Map;

@Service
public class SearchService {

    private static final Logger log = LoggerFactory.getLogger(SearchService.class);

    /**
     * 使用Tavily进行AI搜索
     * @param query 搜索关键词
     * @param maxResults 最大返回结果数
     * @return JSON格式的搜索结果（失败时返回错误信息）
     */
    @Tool(name = "tavilySearch", description = "根据搜索关键词从互联网进行搜索")
    public String tavilySearch(
            @ToolParam(description = "搜索关键词", required = true) String query,
            @ToolParam(description = "最大返回结果数") int maxResults
    ) {
        try {
            TavilySearch tavilySearch = new TavilySearch();
            List<Map<String, String>> results = tavilySearch.tavilySearch(query, maxResults);
            log.error("Tavily search completed for query: {}, results: {}", query, results.size());
            return new ObjectMapper().writeValueAsString(results);
        } catch (Exception e) {
            log.error("Tavily search failed for query: {}", query, e);
            return "{\"error\":\"Search failed: " + e.getMessage() + "\"}";
        }
    }

}
